package custom.base.http.listener;


import android.app.Dialog;
import android.content.Context;

import custom.base.http.data.NetCode;
import custom.base.widgets.LoadLayout;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luozi on 2015/12/29.
 * 响应监听，泛型
 */
public abstract class ResponseStringListener<T> implements Callback<T>, NetCode {
    protected AliveCallback liveNetCallback;
    protected Context context;

    public ResponseStringListener(AliveCallback liveNetCallback) {
        this.liveNetCallback = liveNetCallback;
        this.context = liveNetCallback.currentContext();
    }

    public ResponseStringListener(final Context context) {
        this.context = context;
        this.liveNetCallback = new AliveCallback() {
            @Override
            public boolean isAlive() {
                return true;
            }

            @Override
            public Context currentContext() {
                return context;
            }
        };
    }


    /**
     * 弹框等待绑定
     */
    protected Dialog getDialog() {
        return null;
    }

    /**
     * 布局加载提示绑定
     */
    protected LoadLayout getLoadLayout() {
        return null;
    }


    @Override
    public final void onResponse(Call call, Response response) {
        if (!liveNetCallback.isAlive())//当环境为空的时候拒绝回调，为了避免界面被回收控件为空的问题
            return;

//        BaseResponse<T> baseResponse = (BaseResponse<T>) response.body();
        String res = (String) response.body();
        onResponseSuccess(call, res);
    }

    @Override
    public final void onFailure(Call call, Throwable t) {
        if (!liveNetCallback.isAlive())//当环境为空的时候拒绝回调，为了避免界面被回收控件为空的问题
            return;
        if (call.isCanceled()) {
            onResponseCancel(call, t);
        } else {
            onResponseError(call, t);
        }
    }

    /**
     * 响应成功
     */
    public abstract void onResponseSuccess(Call call, String response);

    /**
     * 请求错误
     */
    public void onResponseError(Call call, Throwable t) {

    }

    /**
     * 取消请求
     * 根据框架而定，暂时弃用
     */
    public void onResponseCancel(Call call, Throwable t) {
    }

}
